import requests
import logging
import json
from src.models.models import SystemConfig, get_beijing_time

# 配置日志
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)

class XunleiNasDownloader:
    """迅雷NAS下载器"""
    
    def __init__(self):
        self.host = SystemConfig.get_config('xunlei_nas_host', 'http://192.168.211.139:52345')
        self.device_space_id = SystemConfig.get_config('xunlei_nas_device_space_id', '')
    
    @property
    def credential(self):
        return SystemConfig.get_config('xunlei_nas_credential', '')
        
    def get_seed_info(self, urls):
        """
        第一步：获取种子信息
        """
        response = None
        try:
            url = f"{self.host}/webman/3rdparty/pan-xunlei-com/index.cgi/drive/v1/resource/list"
            
            headers = {
                'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:139.0) Gecko/20100101 Firefox/139.0',
                'Accept': '*/*',
                'Accept-Language': 'zh-CN,zh;q=0.8,zh-TW;q=0.7,zh-HK;q=0.5,en-US;q=0.3,en;q=0.2',
                'Accept-Encoding': 'gzip, deflate, br',
                'content-type': 'application/json',
                'pan-auth': self.credential
            }
            
            data = {
                "page_size": 1000,
                "urls": urls
            }

            # 显式转换为JSON格式，确保使用双引号
            json_data = json.dumps(data, ensure_ascii=False)
            
            logger.info(f"获取种子信息: {url}")
            logger.info(f"请求数据: {json_data}")
            
            response = requests.post(url, headers=headers, data=json_data, timeout=30)
            
            # 无论是否异常，都打印响应信息
            logger.info(f"响应状态码: {response.status_code}")
            # logger.info(f"响应头: {dict(response.headers)}")
            try:
                logger.info(f"响应内容: {response.text}")
            except Exception as text_error:
                logger.error(f"无法读取响应内容: {str(text_error)}")
            
            response.raise_for_status()
            
            result = response.json()
            # logger.info(f"种子信息响应: {result}")
            
            if 'list' in result and 'resources' in result['list']:
                resources = result['list']['resources']
                if resources:
                    # 返回第一个资源的信息
                    resource = resources[0]
                    return {
                        "success": True,
                        "data": {
                            "name": resource.get("name", ""),
                            "file_size": resource.get("file_size", 0),
                            "file_count": resource.get("file_count", 1),
                            "mime_type": resource.get("meta", {}).get("mime_type", ""),
                            "hash": resource.get("meta", {}).get("hash", ""),
                            "list_id": result.get("list_id", "")
                        }
                    }
                else:
                    return {
                        'success': False,
                        'message': '未找到有效的种子信息'
                    }
            else:
                return {
                    'success': False,
                    'message': '种子信息响应格式错误'
                }
                
        except requests.exceptions.RequestException as e:
            logger.error(f"获取种子信息网络错误: {str(e)}")
            return {
                'success': False,
                'message': f'网络错误: {str(e)}'
            }
        except Exception as e:
            logger.error(f"获取种子信息失败: {str(e)}")
            return {
                'success': False,
                'message': f'获取种子信息失败: {str(e)}'
            }
    
    def create_download_task(self, seed_info, download_url, parent_folder_id):
        """
        第二步：创建下载任务
        """
        try:
            url = f"{self.host}/webman/3rdparty/pan-xunlei-com/index.cgi/drive/v1/task"
            
            headers = {
                'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:139.0) Gecko/20100101 Firefox/139.0',
                'Accept': '*/*',
                'Accept-Language': 'zh-CN,zh;q=0.8,zh-TW;q=0.7,zh-HK;q=0.5,en-US;q=0.3,en;q=0.2',
                'Accept-Encoding': 'gzip, deflate, br',
                'content-type': 'application/json',
                'pan-auth': self.credential
            }
            
            data = {
                "type": "user#download-url",
                "name": seed_info['name'],
                "file_name": seed_info['name'],
                "file_size": str(seed_info['file_size']),
                "space": self.device_space_id,
                "params": {
                    "target": self.device_space_id,
                    "url": download_url,
                    "total_file_count": str(seed_info['file_count']),
                    "parent_folder_id": parent_folder_id,
                    "sub_file_index": "--1,",
                    "mime_type": seed_info['mime_type'],
                    "file_id": ""
                }
            }
            
            # 显式转换为JSON格式，确保使用双引号
            json_data = json.dumps(data, ensure_ascii=False)
            
            logger.info(f"创建下载任务: {url}")
            logger.info(f"请求数据: {json_data}")
            
            response = requests.post(url, headers=headers, data=json_data, timeout=30)

            # 无论是否异常，都打印响应信息
            logger.info(f"响应状态码: {response.status_code}")
            # logger.info(f"响应头: {dict(response.headers)}")
            try:
                logger.info(f"响应内容: {response.text}")
            except Exception as text_error:
                logger.error(f"无法读取响应内容: {str(text_error)}")

            response.raise_for_status()
            
            result = response.json()
            # logger.info(f"创建下载任务响应: {result}")
            
            if result.get('HttpStatus') == 0:
                return {
                    'success': True,
                    'data': result.get('task', {})
                }
            else:
                return {
                    'success': False,
                    'message': f'创建下载任务失败: HttpStatus={result.get("HttpStatus")}'
                }
                
        except requests.exceptions.RequestException as e:
            logger.error(f"创建下载任务网络错误: {str(e)}")
            return {
                'success': False,
                'message': f'网络错误: {str(e)}'
            }
        except Exception as e:
            logger.error(f"创建下载任务失败: {str(e)}")
            return {
                'success': False,
                'message': f'创建下载任务失败: {str(e)}'
            }
    
    def process_download(self, download_url, parent_folder_id):
        """
        完整的下载处理流程
        """
        try:
            # 第一步：获取种子信息
            seed_result = self.get_seed_info(download_url)
            if not seed_result['success']:
                return {
                    'success': False,
                    'status': 'created_failed',
                    'message': seed_result['message']
                }
            
            seed_info = seed_result['data']
            
            # 第二步：创建下载任务
            task_result = self.create_download_task(seed_info, download_url, parent_folder_id)
            if not task_result['success']:
                return {
                    'success': False,
                    'status': 'created_failed',
                    'message': task_result['message']
                }
            
            return {
                'success': True,
                'status': 'created_success',
                'message': '下载任务创建成功',
                'data': {
                    'seed_info': seed_info,
                    'task_info': task_result['data']
                }
            }
            
        except Exception as e:
            logger.error(f"下载处理失败: {str(e)}")
            return {
                'success': False,
                'status': 'created_failed',
                'message': f'下载处理失败: {str(e)}'
            } 